{% extends base.html %}

{% block title %}Zest Console{% end %}


{% block includes %}

<style type="text/css">

body,html,.row-offcanvas {
  height:100%;
}

body {
  padding-top: 50px;
}

#sidebar {
  width: inherit;
  min-width: 220px;
  max-width: 220px;
  background-color:#f5f5f5;
  float: left;
  height:100%;
  position:relative;
  overflow-y:auto;
  overflow-x:hidden;
}

#main {
  height:100%;
  overflow:auto;
}

.btn.zconsolebtn{
  margin:30px;
  padding:7px;

}

.btn:focus,a, a:active, a:focus{
  outline: none;
}

  /* 1st level */
.nav label {
  color: blue;
}

/* 2nd level */
.tree > li > label {
  padding:10px 15px;
}

/* 3rd level */
.tree > li > ul > li > a {
  color:#cc0000;
  font-size:10pt;
  margin-left:15px;
}

.modal-dialog-center{
  width: 320px;
  margin: 0;
  position: absolute;
  top: 35%;
  left: 42%;
}

</style>

{% end %}

{% block content %}
<br/>
<div class="row">
    <ul class="breadcrumb">
        <li>
            <a href="/">Home</a>
        </li>
        <li>
            <a href="/ui/transactions/">Transactions</a>
        </li>
        <li class="active">Zest Console</li>
    </ul>
</div>
<div class="container">
  <div class="row-fluid">
      <div class="col-md-3">
          <div class="well">
              <div>
                  <ul id="allscripts" class="nav nav-stacked fixed">
                      <li>
                          <label label-default="" class="tree-toggle nav-header">Other Recorded Scripts</label>
                          <ul id="rec_scripts" class="nav tree">
                          </ul>
                      </li>
                      <li>
                        <label label-default="" class="tree-toggle nav-header">Zest Scripts in Scope</label>
                        <ul id="tar_scripts" class="nav tree">
                        </ul>
                      </li>

                  </ul>
              </div>
          </div>
      </div>
      <div class="col-md-9">
        <div id="script_detail">
         <div id="script_data">
        <h4>Script Content</h4>
      <pre id="script_content"></pre>
        </div>
       <div id="script_result">
        <h4>Zest Output</h4>
      <pre id="script_output"></pre>
       </div>
     </div>
     <div class="row" style="text-align:center" >
        <button class="btn btn-primary zconsolebtn" onclick="recordToggle()" id="recordZest">Record a Zest Script!</button>
        <button class="btn btn-primary zconsolebtn" id="RunZest" onclick="runZestScript()"> Run the Zest Script !</button>
     </div>

    </div>
  </div>
</div>

<!--Script Name Modal-->
<div class="modal fade" id="ScriptModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog-center">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button"  class="close"  data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Enter Script Name :</h4>
        <h6 class="modal-title" id="name_tip">(only alphanumeric characters)</h6>
      </div>
      <div class="modal-body">
        <p id="Filecheck" style="color:red"></p>
        <input type="text" id="textareaID" class="form-control"></input>
      </div>
      <div class="modal-footer">
         <button type="button" class="btn-primary" id="startBtn" onclick="startRecording()">Start</button>
        <button type="button" class="btn-default"  data-dismiss="modal">Cancel</button>

      </div>
    </div>
  </div>
</div>





<script>

var mySpace = {

                    zest_console_api_url:"{{ zest_console_api_url }}",
                    zest_recording:"{{ zest_recording }}",
                    zest_target_heading:"{{ zest_target_heading }}",
              };

//sets output window and calls runScript
function runZestScript(){
    $("#script_content").css("height","250px");
    $("#script_result").show();
    $("#script_output").text('');
    $("#script_result").css("height","250px");
    var script = $('li .active')
    runScript(script);
}

//actually runs the script by sending script name and type
function runScript(script){
   var id = script.parent().attr('id');
   if (id=="tar_scripts"){
    $.getJSON(mySpace.zest_console_api_url+"?record=false&run=true&script="+script.attr('name'),function(obj){
          setContentResultWindow(obj.result);
    });

   }
   else{
    $.getJSON(mySpace.zest_console_api_url+"?record=true&run=true&script="+script.text(),function(obj){
          setContentResultWindow(obj.result);
    });

   }
    $("#script_output").css("height","220px");
}

//takes output and sets the text of output window (after script running)
function setContentResultWindow(content){
    $("#script_output").text(content);

}

//get scripts in zest output folder of the target
function getScriptNames(){
    $.getJSON(mySpace.zest_console_api_url,function(obj){
    var target_list=obj.target_scripts;
    var rec_list=obj.recorded_scripts;
    loadTargetScriptNames(target_list);
    loadRecordScriptNames(rec_list);
    });
}

//gets the domain specific name for e.g example.com:80-script.zst
function getTargetSpecificName(name){
  return mySpace.zest_target_heading+"-"+name;

}

//loads all the target scripts of the specific target in the sidebar
function loadTargetScriptNames(target_list){
    $("#tar_scripts").empty();
    for (i=0;i<target_list.length;i++){
      if (i==0){
        $("#tar_scripts").append('<li class="active" name='+target_list[i]+'><a href="#">'+
          getTargetSpecificName(target_list[i])+'</a></li>');
        getTargetScriptContent(target_list[i]);
      }
      else{
            $("#tar_scripts").append('<li name='+target_list[i]+'><a href="#">'+getTargetSpecificName(target_list[i])+'</a></li>');
      }
    }
}

// loads names of all the record scripts stored at /owtf_ouput_directory/misc/recorded_scripts/
function loadRecordScriptNames(rec_list){
    $("#rec_scripts").empty();
    for(i=0;i<rec_list.length;i++){
      if (i==0){
        $("#rec_scripts").append('<li name='+rec_list[i]+'><a href="#">'+rec_list[i]+'</a></li>');
      }
      else{
          $("#rec_scripts").append('<li name='+rec_list[i]+'><a href="#">'+rec_list[i]+'</a></li>');
      }
    }
    $("#rec_scripts").hide();
}

// sets record button while loading zest console
function setRecordButton(){
    if(mySpace.zest_recording=="True"){
      recordOn();
    }
    else{
      recordOff();
    }
}

//sets zest record button to on and off
function recordOn(){
    $('#recordZest').attr('class','btn btn-danger');
    $('#recordZest').text('Stop Recording !');
}

function recordOff(){
    $('#recordZest').attr('class','btn btn-primary');
    $('#recordZest').text('Record a Zest Script!');
}

//checks filename contains alpha-numeric characters using regex.
function validateFilename(elem){

        var alphaExp = /^[0-9a-zA-Z]+$/;
        //  var alphaExp=/^[\w,\s-]+/
        if(elem.match(alphaExp)){
          return true;
        }
        else{
          $("#Filecheck").text("Script name invalid !");
        }
}

// focuses/clears textbox in script modal window
$('#ScriptModal').on('show.bs.modal', function (e) {

        $('#textareaID').focus();
        ClearText("textareaID");
        $("#Filecheck").text('');
});

//clears text
function ClearText(id){

        id='#'+id;
        $(id).val('');
}

//validates filename and sets recording on by updating "ZEST_RECORDING" as true in config
function startRecording(){
     var file_name=$('#textareaID').val();
     //validates file name using regex
     if(validateFilename(file_name)){

        $.ajax({
            url:mySpace.zest_console_api_url+"?record=true&file="+file_name,
            type:'GET',
            success:checkIfFileExists,
            error:function(xhr, textStatus, serverResponse){
            alert("Server replied: "+serverResponse);
                }

            });
      }


}

//Toggles the record button
function recordToggle(){
    if (mySpace.zest_recording=="False"){

     $('#ScriptModal').modal('show');
    }
    else{
      $.getJSON(mySpace.zest_console_api_url+"?record=false");
      recordOff();
      mySpace.zest_recording = "False";

    }
}

//Checks whether file exists else success
function checkIfFileExists(data, Status, xhr){

        if(data.exists!="true"){
           $('#ScriptModal').modal('hide');
           alertSuccess("Script Created :D");
           recordOn();
           mySpace.zest_recording = "True";

        }
        else{
           $("#Filecheck").text("Script with this name already exists !");
        }

}

//get content of the active script
function getTargetScriptContent(script){
    $.getJSON(mySpace.zest_console_api_url+"?record=false&script="+script,function(obj){
          setContentWindow(obj.content);
    });
}

//sets the scripts content of the selected zest script
function setContentWindow(content){

   $("#script_content").text(content);
   $("#script_content").css("height","500px");
   $("#script_result").hide();
}

//fetches record script content
function getRecordScriptContent(script){
    $.getJSON(mySpace.zest_console_api_url+"?record=true&script="+script,function(obj){
          setContentWindow(obj.content);
    });
}

$('.tree-toggle').click(function (){
  $(this).parent().children('ul.tree').toggle(200);
});

//sidebar click event delegation
$('#allscripts').on('click','a', function (e) {
    $('li').removeClass('active');
    var $parent = $(this).parent();
    if (!$parent.hasClass('active')) {
      $parent.addClass('active');
      var script = $parent.attr('name');
      $p_par = $parent.parent();
      var script_t = $p_par.attr('id');
      if(script_t=="tar_scripts"){
        getTargetScriptContent(script);
      }
      else if (script_t == "rec_scripts"){
        getRecordScriptContent(script);
      }
    }
    e.preventDefault();
});

$(document).ready(function() {
  $('[data-toggle=offcanvas]').click(function() {
    $('.row-offcanvas').toggleClass('active');
  });
  getScriptNames();
  setRecordButton();
  $("#script_result").hide();
  updateBreadCrumb();
});

</script>

{% end %}
